<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaName">
              <a-input v-model="model.formulaName" placeholder="请输入名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="公式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaExpression">
              <a-input v-model="model.formulaExpression" placeholder="请输入公式" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="配方性质" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaAttribute">
              <j-dict-select-tag type="list" v-model="model.formulaAttribute" dictCode="formula_attribute" placeholder="请选择配方性质" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="配方公式明细" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="ipsFormulaDetailTable.loading"
          :columns="ipsFormulaDetailTable.columns"
          :dataSource="ipsFormulaDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import { ajaxGetDictItems } from '@api/api'

  export default {
    name: 'IpsFormulaInfoForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           formulaName: [
              { required: true, message: '请输入名称!'},
           ],
           formulaExpression: [
              { required: true, message: '请输入公式!'},
           ],
           formulaAttribute: [
              { required: true, message: '请输入配方性质!'},
           ],
        },
        refKeys: ['ipsFormulaDetail', ],
        tableKeys:['ipsFormulaDetail', ],
        activeKey: 'ipsFormulaDetail',
        // 配方公式明细
        ipsFormulaDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料ID',
              key: 'materialId',
              type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料编码',
              key: 'materialCode',
              type: JVXETypes.popup,
              popupCode:"formula_material_detail",
              field:"id,code,name,none_spec,me_unit,category_no,category_name",
              orgFields:"id,code,name,none_spec,me_unit,category_no,category_name",
              destFields:"materialId,materialCode,materialName,materialSpec,materialUnit,materialCategoryNo,materialCategoryName",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料名称',
              key: 'materialName',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: '规格型号',
              key: 'materialSpec',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: '单位',
              key: 'materialUnit',
              type: JVXETypes.input,
              dictCode:"ji_unit",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
              formatter: ({cellValue}) => {
                const item = this.dictInfos.find(item => item.value === cellValue);
                return item ? item.text : cellValue;
              }
            },
            {
              title: '种类编号',
              key: 'materialCategoryNo',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: '种类名称',
              key: 'materialCategoryName',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },

            {
              title: 'material_id',
              key: 'material_id',
              type:"hidden"
            },

            {
              title: 'material_code',
              key: 'material_code',
              type:"hidden"
            },

            {
              title: 'material_name',
              key: 'material_name',
              type:"hidden"
            },

            {
              title: 'material_spec',
              key: 'material_spec',
              type:"hidden"
            },

            {
              title: 'material_unit',
              key: 'material_unit',
              type:"hidden"
            },

            {
              title: 'material_category_no',
              key: 'material_category_no',
              type:"hidden"
            },

            {
              title: 'material_category_name',
              key: 'material_category_name',
              type:"hidden"
            },
          ]
        },
        url: {
          add: "/ipsformulainfo/ipsFormulaInfo/add",
          edit: "/ipsformulainfo/ipsFormulaInfo/edit",
          queryById: "/ipsformulainfo/ipsFormulaInfo/queryById",
          ipsFormulaDetail: {
            list: '/ipsformulainfo/ipsFormulaInfo/queryIpsFormulaDetailByMainId'
          },
        },
        dictInfos: [],
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      loadDictData() {
        ajaxGetDictItems('ji_unit', null).then((res) => {
          if (res.success) {
            this.dictInfos = res.result
          }
        })
      },
      addBefore(){
        this.ipsFormulaDetailTable.dataSource=[]
        this.loadDictData()
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        if (this.model.id) {
          ajaxGetDictItems('ji_unit', null).then((res) => {
            if (res.success) {
              this.dictInfos = res.result
              // 加载子表数据
              let params = { id: this.model.id }
              this.requestSubTableData(this.url.ipsFormulaDetail.list, params, this.ipsFormulaDetailTable)
            }
          })
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          ipsFormulaDetailList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      request(formData) {
        let url = this.url.add, method = 'post'
        if (this.model.id) {
          url = this.url.edit
          method = 'put'
        }
        this.confirmLoading = true
        console.log("formData===>",formData);
        httpAction(url, formData, method).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning({
              content: this.$createElement('div',
                res.message.split('\n').map(text =>
                  this.$createElement('div', text)
                )
              ),
              duration: 5
            });
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },
    }
  }
</script>

<style scoped>
</style>